/*
 * Created on 2005-11-11
 *
 */
package com.yl.cap.analyst.report.chart.maker;

import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import com.yl.cap.analyst.report.chart.data.ChartData;
import com.yl.cap.analyst.report.chart.data.Point;
import com.yl.cap.analyst.report.chart.data.XYLineChartData;

public class XYLineMaker extends ChartMaker
{
    public void makeChart(String fileName, ChartData data) throws Exception
    {
        XYLineChartData chartData = (XYLineChartData) data;
        //create dataset
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = null;
        Set set = chartData.getSeries().entrySet();
        Iterator it = set.iterator();
        Entry entry = null;
        List list = null;
        Point p = null;
        while (it.hasNext())
        {
            entry = (Entry) it.next();
            series = new XYSeries(entry.getKey().toString());
            list = (List)entry.getValue();
            for (int i = 0; i < list.size(); i++)
            {
                p = (Point)list.get(i);
                series.add(p.getX(),p.getY());
            }
            dataset.addSeries(series);
        }
        //==========================
        JFreeChart chart = ChartFactory.createXYLineChart(
                data.getCaption(), // chart title
                chartData.getXCaption(), // x axis label
                chartData.getYCaption(), // y axis label
                dataset, // data
                PlotOrientation.VERTICAL,
                true, // include legend
                true, // tooltips
                false // urls
                );
        FileOutputStream fos_jpg = null;
        try
        {
            fos_jpg = new FileOutputStream(fileName);
            ChartUtilities.writeChartAsJPEG(fos_jpg, 100, chart, data
                    .getWidth(), data.getHeight(), null);
        }
        catch (Exception e)
        {
            fos_jpg.close();
            throw e;
        }
        fos_jpg.close();
    }
}
